package com.kyrioscraft.cloud.thead.jdklab.tools.reentrant;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author kyrioscraft
 * @Date 2019/2/18 13:52
 * @Description 读写分离的思想，读和读不互斥，readLock加锁后读线程同时执行锁内代码
 **/
public class ReadWriteLockDemo {
    private static Lock lock = new ReentrantLock();
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();
    private int value;

    public Object handleRead(Lock lock) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println(System.currentTimeMillis()+' '+ Thread.currentThread().getId()+" 读操作执行完毕");
            return value;
        } finally {
            lock.unlock();
        }
    }

    public void handleWrite(Lock lock, int index) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            value=index;
            System.out.println(System.currentTimeMillis()+' '+ Thread.currentThread().getId()+" 写操作执行完毕");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final ReadWriteLockDemo demo = new ReadWriteLockDemo();
        Runnable readRunnale=()->{
            try {
                demo.handleRead(readLock);

            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Runnable writeRunnale=()->{
          try {
              demo.handleWrite(writeLock,new Random().nextInt());
          } catch (InterruptedException e){
              e.printStackTrace();
          }
        };

        for(int i=0; i<18; i++) {
            new Thread(readRunnale).start();
        }

        for(int i=18; i<30; i++) {
            new Thread(writeRunnale).start();
        }
    }
}
